import {
	showSuccess,
	showToast
} from "@/core/app"
import {
	ref
} from "vue";
import {
	getPayList,
	prePayment
} from "@/api/pay.js";
/**
 * 支付列表以及拉起支付
 * @param {boolean} isGetPaymentList:false    是否立即执行获取列表 
 */
// 支付列表是全局的
const payList = ref([])
export const useRequestPayment = () => {
	// 获取支付列表
	const getPayListData = async (type = "wechat_applet") => {
		let res = await getPayList({
			type
		})
		if (res) {
			payList.value = res.data.map(item => {
				if (item.type == 'wechat_applet') item.type = 'wxpay'
				return item
			})
			return res.data
		}
	}
	// 获取支付列表中指定的支付方式
	const getPayItem = (type, key) => {
		let res
		if (payList.value && payList.value.length > 0) res = payList.value.find(item => item.type == type)
		if (res[key]) res = res[key]
		return res
	}
	/**
	 * 预支付,获取拉起支付的数据
	 * @param {object}  {payment_code:'',order_no:''}
	 */
	const getPrePaymentData = async (parmas) => {
		let res = await prePayment(parmas)
		if (res) {
			return res.data
		}
	}
	/**
	 * @description 拉起微信支付和支付宝支付
	 * @param {String}   provider:'wxpay'|'alipay'
	 * @param {Object|String}   orderInfo:{}|''
	 */
	const toPay = (provider, orderInfo = {}) => {
		return new Promise((resolve, reject) => {
			// #ifdef APP
			uni.requestPayment({
				provider,
				orderInfo,
				success: res => {
					return resolve(true)
				},
				fail: res => {
					return resolve(false)
				},
				complete: (e) => {
					console.log(e);
				}
			})
			// #endif
			// #ifdef MP-WEIXIN
			uni.requestPayment({
				provider: provider,
				timeStamp: orderInfo.timeStamp,
				nonceStr: orderInfo.nonceStr,
				package: orderInfo.package,
				signType: 'MD5',
				paySign: orderInfo.paySign,
				success: res => resolve(true),
				fail: res => resolve(false)
			})
			// #endif
		})
	}
	return {
		payList,
		getPayListData,
		getPayItem,
		getPrePaymentData,
		toPay
	}
}